import requests
import re
import time
from datetime import datetime, timezone
import os
import pytz

# 记录最新公告的时间戳（初始为0）
latest_timestamp = 0


def fetch_announcement_titles_with_keyword(keyword, sendkey):
    global latest_timestamp
    url = "https://api.bitget.com/api/v2/public/annoucements?language=zh_CN"

    try:
        response = requests.get(url)

        if response.status_code == 200:
            data = response.json()  # 解析JSON
            announcements = data['data']  # 获取公告数据列表

            # 找到包含关键词的公告标题
            filtered_announcements = [
                item for item in announcements if keyword in item.get('annTitle', '')
            ]

            if filtered_announcements:
                print("找到以下包含关键词的公告:")
                for item in filtered_announcements:
                    title = item['annTitle']
                    url = item['annUrl']
                    try:
                        # 获取毫秒级时间戳并转换为秒级别的时间
                        timestamp_ms = int(item['cTime'])
                        timestamp_s = timestamp_ms / 1000.0

                    except(ValueError,TypeError):
                        print(f"公告 {item.get('annTitle', '未知标题')}的时间戳无效，忽略。")
                        continue # 跳过当前公告

                    # 检查是否是最新的公告
                    if timestamp_s > latest_timestamp:
                        latest_timestamp = timestamp_s  # 更新最新时间戳
                        # 将时间戳转换为可读的时间格式(使用UTC+8时区)
                        tz = pytz.timezone("Asia/Shanghai") # 设置为上海市区

                        # readable_time = datetime.utcfromtimestamp(timestamp_s).strftime('%Y-%m-%d %H:%M:%S')
                        readable_time = datetime.fromtimestamp(timestamp_s,tz).strftime("%Y-%m-%d %H:%M:%S")
                        print(title)
                        print(url)
                        print(readable_time)

                        # 调用sc_send函数发送消息到微信
                        message_title = "新公告提示"
                        message_desp = f"标题: {title}\n时间: {readable_time}\n链接: {url}"
                        sc_send(sendkey, message_title, message_desp)
                    else:
                        print(f"公告 '{title}' 已存在，忽略。")
            else:
                print(f"未找到包含关键词 '{keyword}' 的公告。")

        else:
            print(f"请求失败，状态码: {response.status_code}")

    except Exception as e:
        print(f"请求时出现错误: {e}")

#  向微信推送消息
def sc_send(sendkey, title, desp='', options=None):
    if options is None:
        options = {}
    # 判断 sendkey 是否以 'sctp' 开头，并提取数字构造 URL
    if sendkey.startswith('sctp'):
        match = re.match(r'sctp(\d+)t', sendkey)
        if match:
            num = match.group(1)
            url = f'https://{num}.push.ft07.com/send/{sendkey}.send'
        else:
            raise ValueError('Invalid sendkey format for sctp')
    else:
        url = f'https://sctapi.ftqq.com/{sendkey}.send'
    params = {
        'title': title,
        'desp': desp,
        **options
    }
    headers = {
        'Content-Type': 'application/json;charset=utf-8'
    }
    response = requests.post(url, json=params, headers=headers)
    result = response.json()
    return result

# 向微信推送消息
def sc_send(sendkey, title, desp='', options=None):
    if options is None:
        options = {}
    # 判断 sendkey 是否以 'sctp' 开头，并提取数字构造 URL
    if sendkey.startswith('sctp'):
        match = re.match(r'sctp(\d+)t', sendkey)
        if match:
            num = match.group(1)
            url = f'https://{num}.push.ft07.com/send/{sendkey}.send'
        else:
            raise ValueError('Invalid sendkey format for sctp')
    else:
        url = f'https://sctapi.ftqq.com/{sendkey}.send'
    params = {
        'title': title,
        'desp': desp,
        **options
    }
    headers = {
        'Content-Type': 'application/json;charset=utf-8'
    }
    response = requests.post(url, json=params, headers=headers)
    result = response.json()
    return result

if __name__ == "__main__":
    keyword = "盘前交易"

    # 定时获取公告的例子
    while True:
        data = {}
        with open(os.path.join(os.path.dirname(__file__), 'env', 'data.env'), 'r') as f:
            for line in f:
                key, value = line.strip().split('=')
                data[key] = value
        key = data['SENDKEY']
        fetch_announcement_titles_with_keyword(keyword=keyword,sendkey=key)
        time.sleep(18000)  # 保证每天循环次数不超过5次